package util;

import entity.Employee;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDate;

public class EmployeeUtil extends HttpServlet {

    public static Employee getEmployeeByForm(HttpServletRequest req) {
        //1.获取请求参数
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String birthday = req.getParameter("birthday");
        String gender = req.getParameter("gender");
        String phone = req.getParameter("phone");
        // System.out.println(name + birthday + gender + phone);
        //创建employee对象
        Employee employee = new Employee(Integer.parseInt(id),name,
                LocalDate.parse(birthday), Integer.parseInt(gender.trim()), phone);
        return employee;
    }

    public static Employee getEmployeeByForm2(HttpServletRequest req) {
        //1.获取请求参数
        String id = req.getParameter("default-id");
        String name = req.getParameter("name");
        String birthday = req.getParameter("birthday");
        String gender = req.getParameter("gender");
        String phone = req.getParameter("phone");
        System.out.println(id);
        //创建employee对象
        Employee employee = new Employee(Integer.parseInt(id),name,
                LocalDate.parse(birthday), Integer.parseInt(gender.trim()), phone);
        return employee;
    }

    public static Employee getEmployeeByID(HttpServletRequest req) {
        //1.获取请求参数
        String id = req.getParameter("id");
        System.out.println(id);
        //创建employee对象
        Employee employee = new Employee(Integer.parseInt(id.trim()));
        return employee;
    }

    public static Employee getEmployeeByIDAndURL(String url) throws IOException {
        URL urll = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) urll.openConnection();
        InputStream inputStream = connection.getInputStream();
        String res = readInputStream(inputStream);
        String[] urls = res.split("=");
        Employee employee = new Employee(Integer.parseInt(urls[1].trim()));
        return employee;
    }

    public static String readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        System.out.println(new String(bos.toByteArray(), "utf-8"));
        return new String(bos.toByteArray(), "utf-8");
    }
}
